package com.yanghui.service.impl;

import com.yanghui.dao.BlogMapper;
import com.yanghui.dao.BlogTypeMapper;
import com.yanghui.pojo.*;
import com.yanghui.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private BlogTypeMapper blogTypeMapper;


    /**
     * 查询上一篇博客
     */
    @Override
    public Blog selectPrevBlog(Integer id) {
        return blogMapper.selectPrevBlog(id);
    }

    /**
     * 按照查询条件模糊查询博客
     */
    @Override
    public List<Blog> selectLikeBlogListByPage(Map<String, Object> map) {
        List<Blog> blogList = blogMapper.selectLikeBlogListByPage(map);

        for (Blog blog : blogList) {
            BlogType blogType = blogTypeMapper.selectByPrimaryKey(blog.getTypeId());
            blog.setTypeName(blogType.getTypeName());
        }

        return blogList;
    }

    /**
     * 查询下一篇博客
     */
    @Override
    public Blog selectNextBlog(Integer id) {
        return blogMapper.selectNextBlog(id);
    }

    /**
     * 按照博客点击量降序
     * 取出前几条数据
     * id,clickNum
     * 可以通过id查看对应的博客信息
     */
    @Override
    public List<?> selectBlogByClick() {
        return blogMapper.selectBlogByClick();
    }

    /**
     * 按照指定日期查询博客
     */
    @Override
    public List<?> selectBlogByDate(Map<String, Object> map) {
        return blogMapper.selectBlogByDate(map);
    }

    /**
     * 把所有的博客类别都查询出前N篇博客
     * @return
     */
    @Override
    public Map<String, List<Blog>> selectBlogByAllType() {
        Map<String, List<Blog>> map = new HashMap<>();
        List<Blog> list = blogMapper.selectBlogByAllType();

        /** 按照 typeId 查询出 typeName */
        for (Blog blog : list) {
            BlogType blogType = blogTypeMapper.selectByPrimaryKey(blog.getTypeId());
            blog.setTypeName(blogType.getTypeName());
        }

        /** 按类别归类 */
        for (Blog blog : list) {
            if (map.containsKey(blog.getTypeName())) {
                map.get(blog.getTypeName()).add(blog);
            } else {
                List<Blog> bList = new ArrayList<>();
                bList.add(blog);
                map.put(blog.getTypeName(), bList);
            }
        }

        return map;
    }

    /**
     * 按照指定日期查询博客数量
     */
    @Override
    public Map<Object, Object> selectBlogListByDate(Map map) {
        Map<Object,Object> resultMap = new HashMap<>();

        BlogExample blogExample = new BlogExample();
        BlogExample.Criteria criteria = blogExample.createCriteria();

        BlogExample blogExample1 = new BlogExample();
        BlogExample.Criteria criteria1 = blogExample1.createCriteria();

        BlogExample blogExample2 = new BlogExample();
        BlogExample.Criteria criteria2 = blogExample2.createCriteria();



        Date startTime = (Date) map.get("startTime");
        Date endTime = (Date) map.get("endTime");
        Integer status = (Integer) map.get("status");

        if (status != null) {
            criteria.andStatusEqualTo(status);
        }

        if (startTime != null && "".equals(startTime) != true) {
            if (endTime != null && "".equals(endTime) != true) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startTime);
                calendar.add(Calendar.DAY_OF_MONTH, -1 );
                Date yesterdayTime = calendar.getTime();

                calendar.setTime(endTime);
                calendar.add(Calendar.DAY_OF_MONTH, -1 );
                Date midTime = calendar.getTime();

                criteria.andAddTimeBetween(yesterdayTime, startTime);
                List<Blog> list = blogMapper.selectByExample(blogExample);
                String startTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(startTime);
                resultMap.put(startTimeStr, list.size());

                criteria1.andAddTimeBetween(startTime, midTime);
                list = blogMapper.selectByExample(blogExample1);
                String midTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(midTime);
                resultMap.put(midTimeStr, list.size());

                criteria2.andAddTimeBetween(midTime, endTime);
                list = blogMapper.selectByExample(blogExample2);
                String enTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(endTime);
                resultMap.put(enTimeStr, list.size());
            }
        }

        return resultMap;
    }

    /**
     * 更新博客
     */
    @Override
    public int updateBlog(Blog blog) {
        return blogMapper.updateByPrimaryKeySelective(blog);
    }

    /** 按照博客状态查询博客 */
    @Override
    public List<?> selectBlogListByStatus() {
        return blogMapper.selectBlogListByStatus();
    }

    /**
     * 按照博客id查询对应的博客
     */
    @Override
    public Blog selectBlogById(Integer id) {
        Blog blog = blogMapper.selectByPrimaryKey(id);
        BlogType blogType = blogTypeMapper.selectByPrimaryKey(blog.getTypeId());
        blog.setTypeName(blogType.getTypeName());
        return blogMapper.selectByPrimaryKey(id);
    }

    /**
     * 按照给定的条件查询博客
     * 如标题、关键字、博客状态条件
     * 以及是否按照某个字段进行排序
     */
    @Override
    public List<Blog> selectGroupLikeBlogListByPage(Map<String, Object> map) {
        /** 获取要查询的条件 */
        String title = (String) map.get("title");
        String keyword = (String) map.get("keyword");
        String sort = (String) map.get("sort");
        Integer status = (Integer) map.get("status");
        Integer recommend = (Integer) map.get("recommend");
        Integer isTop = (Integer) map.get("isTop");

        BlogExample blogExample = new BlogExample();
        BlogExample.Criteria criteria = blogExample.createCriteria();

        /** 将要查询的条件封装到sql语句中 */
        if (title != null) {
            criteria.andTitleLike("%" + title + "%");
        } else if (keyword != null) {
            criteria.andKeywordLike("%" + keyword + "%");
        } else if (recommend != null) {
            criteria.andIsRecommendEqualTo(recommend);
        } else if (isTop != null) {
            criteria.andIsTopEqualTo(isTop);
        }
        /** 按某个字段排序，默认为升序，可以在后面加 DESC，就是降序 */
        else if (sort != null) {
            // blogExample.setOrderByClause(sort + " desc");
            /** 注意必须得加一个空格 */
            blogExample.setOrderByClause(sort + " desc");
        }
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }

        /** 按照博客类型ID得到博客类型名称 */
        List<Blog> blogList = blogMapper.selectByExample(blogExample);
        for (Blog blog : blogList) {
            BlogType blogType = blogTypeMapper.selectByPrimaryKey(blog.getTypeId());
            blog.setTypeName(blogType.getTypeName());
        }

        return blogList;
    }

    /**
     * 按照博客状态查询博客的数量
     * 三种状态：
     * 草稿（-1）、已经发表（1）、回收站（2）
     * @return
     */
    @Override
    public List<BlogStatus> selectBlogCountByStatus() {
        List<BlogStatus> countList = new ArrayList<>();
        BlogExample blogExample1 = new BlogExample();
        BlogExample.Criteria criteria1 = blogExample1.createCriteria();

        /** 草稿数量 */
        criteria1.andStatusEqualTo(-1);
        int draftCount = (int) blogMapper.countByExample(blogExample1);
        countList.add(new BlogStatus(-1, draftCount));


        /** 已发表数量 */
        BlogExample blogExample2 = new BlogExample();
        BlogExample.Criteria criteria2 = blogExample2.createCriteria();
        criteria2.andStatusEqualTo(1);
        int publishCount = (int) blogMapper.countByExample(blogExample2);
        countList.add(new BlogStatus(1, publishCount));

        /** 回收站数量 */
        BlogExample blogExample3 = new BlogExample();
        BlogExample.Criteria criteria3 = blogExample3.createCriteria();
        criteria3.andStatusEqualTo(2);
        int recycleCount = (int) blogMapper.countByExample(blogExample3);
        countList.add(new BlogStatus(2, recycleCount));

        return countList;
    }

    /**
     * 实现添加博客功能
     * 同时需要把对应的博客类别的数量更新
     */
    @Override
    public int addBlog(Blog blog) {
        int count = blogMapper.insert(blog);

        if (count == 1) {
            BlogType blogType = blogTypeMapper.selectByPrimaryKey(blog.getTypeId());
            blogType.setNum(blogType.getNum() + 1);
            blogTypeMapper.updateByPrimaryKeySelective(blogType);
        }

        return count;
    }

}
